package com.onsproject.nzbgetremote;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class LoggingFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		return inflater.inflate(R.layout.logging_fragment, container, false);
	}

	@Override
	public void onResume() {
		super.onResume();
		mInitialLoadTask.execute("");
	}

	private AsyncTask<String, String, Object[]> mInitialLoadTask = new AsyncTask<String, String, Object[]>() {

		@Override
		protected Object[] doInBackground(String... params) {
			Settings settings = Settings.getInstance(getActivity());
			return (Object[]) settings.callMethod(getActivity(), "log", 0, 50);
		}

		@Override
		protected void onPostExecute(Object[] result) {

			LinearLayout scroll = (LinearLayout) getActivity().findViewById(R.id.scrollLog);

			for (Object log : result) {
				HashMap<String, String> logMap = (HashMap<String, String>) log;

				String kind = getColorString(logMap.get("Kind"));

				TextView text = new TextView(getActivity());
		        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
		        Calendar calendar = Calendar.getInstance();
		        calendar.setTimeInMillis(Long.valueOf(String.valueOf(logMap.get("Time"))) * 1000);

				text.setText(Html.fromHtml(kind + " @ " + formatter.format(calendar.getTime()) + "<br>" + logMap.get("Text")));
				scroll.addView(text);
			}
		};
	};

	private String getColorString(String kind) {
		if (kind.equals("ERROR")) {
			kind = "<font color='#FF0000'>" + kind + "</font>";
		} else if (kind.equals("WARNING")) {
			kind = "<font color='#FF8800'>" + kind + "</font>";
		} else if (kind.equals("INFO")) {
			kind = "<font color='#00F000'>" + kind + "</font>";
		} else if (kind.equals("DEBUG")) {
			kind = "<font color='#0000FF'>" + kind + "</font>";
		}
		return kind;
	}
}
